package net.chasing.retrofit.util.encode;

import android.util.Base64;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class DesUtils {
    private static final String TRANSFORMATION = "DES/CBC/PKCS5Padding";//DES是加密方式 CBC是工作模式 PKCS5Padding是填充模式
    private static final String IVPARAMETERSPEC = "GZW@*78=";////初始化向量参数，AES 为16bytes. DES 为8bytes.
    private static final String ALGORITHM = "DES";//DES是加密方式
    private static final String DES_KEY = "@$+WG#}]";

    /**
     * 获取解码后的值
     */
    public static String decodeBase64(String data) {
        try {
            return decodeBase64(DES_KEY, Base64.decode(data, Base64.DEFAULT));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * DES算法，解密
     *
     * @param data 待解密字符串
     * @param key  解密私钥，长度不能够小于8位
     * @return 解密后的字节数组
     */
    private static String decodeBase64(String key, byte[] data) {
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            IvParameterSpec iv = new IvParameterSpec(IVPARAMETERSPEC.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, getRawKey(key), iv);
            byte[] original = cipher.doFinal(data);
            return new String(original);
        } catch (Exception e) {
            return null;
        }
    }

    // 对密钥进行处理
    private static Key getRawKey(String key) throws Exception {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        return keyFactory.generateSecret(dks);
    }

    /**
     * 加密字符串
     *
     * @param data 需加密的字符串
     * @return 加密后的字符串
     */
    public static String encodeBase64(String data) {
        try {
            IvParameterSpec iv = new IvParameterSpec(IVPARAMETERSPEC.getBytes());
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, getRawKey(DES_KEY), iv);
            byte[] original = cipher.doFinal(data.getBytes());
            String encodeStr = Base64.encodeToString(original, Base64.DEFAULT);
            if (encodeStr != null) encodeStr = encodeStr.replace("\n", "");
            return encodeStr;
        } catch (Exception ignored) {
        }
        return null;
    }
}
